Creating a JavaScript CAPTCHA validation is an essential step in protecting web forms from automated bots and spam. CAPTCHA (Completely Automated Public Turing test to tell Computers and Humans Apart) is a challenge-response test that distinguishes between human users and bots. In this example, I'll show you how to create a simple text-based CAPTCHA validation using JavaScript.
```html
```
```js
// Generate a random CAPTCHA code
function generateRandomCode(length) {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let code = "";
for (let i = 0; i < length; i++) {
code += charset.charAt(randomIndex);
}
return code;
}
// Generate a new CAPTCHA image and code
function generateCaptcha() {
const captchaImage = document.getElementById("captchaImage");
const captchaCode = generateRandomCode(6); // You can adjust the length of the CAPTCHA code here
// For simplicity, we'll display the CAPTCHA code directly as an image
}
// Validate the entered CAPTCHA code
function validateForm() {
const captchaInput = document.getElementById("captchaInput").value.trim();
const captchaImageCode = atob(document.getElementById("captchaImage").src.split(",")[1]);
if (captchaInput === captchaImageCode) {
alert("CAPTCHA validation successful! Form can be submitted.");
return true;
} else {
alert("CAPTCHA validation failed! Please try again.");
return false;
}
}
// Generate the initial CAPTCHA on page load
generateCaptcha();
```
In this example, we generate a random CAPTCHA code with a length of 6 characters, but you can adjust the length in the `generateRandomCode` function. The CAPTCHA code is displayed as an image for simplicity, but in real-world scenarios, you would typically use more complex CAPTCHA images or audio challenges.
When the user clicks the "Generate New CAPTCHA" button, a new CAPTCHA image and code are created. The user needs to enter the CAPTCHA code correctly in the input field to validate the form submission.
Please note that while this simple example demonstrates how to create a basic CAPTCHA, there are more sophisticated CAPTCHA solutions available for production use to enhance security against bots and spammers.